﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace StarSkipGame
{
    public partial class Form1 : Form
    {
        // 游戏引擎
        private GameEngine gameEngine;
        
        // 双缓冲绘图
        private BufferedGraphics bufferedGraphics;
        private BufferedGraphicsContext context;
        
        // 键盘状态
        private bool[] keyStates = new bool[256];
        
        public Form1()
        {
            InitializeComponent();
            InitializeGame();
        }
        
        /// <summary>
        /// 初始化游戏
        /// </summary>
        private void InitializeGame()
        {
            // 设置窗体属性
            this.Text = "星际躲避游戏";
            this.Size = new Size(800, 600);
            this.StartPosition = FormStartPosition.CenterScreen;
            this.FormBorderStyle = FormBorderStyle.FixedSingle;
            this.MaximizeBox = false;
            this.DoubleBuffered = true;

            // 创建菜单栏
            CreateMenuBar();
            
            // 设置窗体样式以支持双缓冲
            SetStyle(ControlStyles.AllPaintingInWmPaint | 
                    ControlStyles.UserPaint | 
                    ControlStyles.DoubleBuffer, true);
            
            // 创建游戏引擎
            gameEngine = new GameEngine(ClientSize.Width, ClientSize.Height);
            
            // 订阅游戏事件
            gameEngine.GameStateChanged += OnGameStateChanged;
            gameEngine.GameTimeUpdated += OnGameTimeUpdated;
            gameEngine.GameOver += OnGameOver;
            gameEngine.AchievementUnlocked += OnAchievementUnlocked;
            gameEngine.RenderRequested += () => Invalidate(); // 订阅渲染请求事件
            gameEngine.DemoRestartRequested += OnDemoRestartRequested; // 订阅演示重启请求事件
            
            // 初始化双缓冲
            context = BufferedGraphicsManager.Current;
            context.MaximumBuffer = new Size(ClientSize.Width + 1, ClientSize.Height + 1);
            bufferedGraphics = context.Allocate(CreateGraphics(), 
                new Rectangle(0, 0, ClientSize.Width, ClientSize.Height));
            
            // 设置键盘事件
            this.KeyDown += Form1_KeyDown;
            this.KeyUp += Form1_KeyUp;
            this.Paint += Form1_Paint;
            
            // 触发初始渲染
            Invalidate();
        }
        
        /// <summary>
        /// 创建菜单栏
        /// </summary>
        private void CreateMenuBar()
        {
            MenuStrip menuStrip = new MenuStrip();
            
            // 游戏菜单
            ToolStripMenuItem gameMenu = new ToolStripMenuItem("游戏(&G)");
            
            ToolStripMenuItem newGameItem = new ToolStripMenuItem("新游戏(&N)", null, NewGame_Click);
            newGameItem.ShortcutKeys = Keys.Control | Keys.N;
            
            ToolStripMenuItem pauseItem = new ToolStripMenuItem("暂停(&P)", null, Pause_Click);
            pauseItem.ShortcutKeys = Keys.Control | Keys.P;
            
            ToolStripMenuItem resumeItem = new ToolStripMenuItem("继续(&R)", null, Resume_Click);
            resumeItem.ShortcutKeys = Keys.Control | Keys.R;
            
            ToolStripMenuItem demoItem = new ToolStripMenuItem("演示模式(&D)", null, Demo_Click);
            demoItem.ShortcutKeys = Keys.Control | Keys.D;
            
            ToolStripSeparator separator1 = new ToolStripSeparator();
            
            ToolStripMenuItem exitItem = new ToolStripMenuItem("退出(&X)", null, Exit_Click);
            exitItem.ShortcutKeys = Keys.Alt | Keys.F4;
            
            gameMenu.DropDownItems.AddRange(new ToolStripItem[] 
            {
                newGameItem, pauseItem, resumeItem, demoItem, separator1, exitItem
            });
            
            // 设置菜单
            ToolStripMenuItem settingsMenu = new ToolStripMenuItem("设置(&S)");
            
            ToolStripMenuItem gameSettingsItem = new ToolStripMenuItem("游戏设置(&G)", null, GameSettings_Click);
            ToolStripMenuItem statisticsItem = new ToolStripMenuItem("游戏统计(&T)", null, Statistics_Click);
            
            settingsMenu.DropDownItems.AddRange(new ToolStripItem[] 
            {
                gameSettingsItem, statisticsItem
            });
            
            // 帮助菜单
            ToolStripMenuItem helpMenu = new ToolStripMenuItem("帮助(&H)");
            
            ToolStripMenuItem aboutItem = new ToolStripMenuItem("关于(&A)", null, About_Click);
            
            helpMenu.DropDownItems.Add(aboutItem);
            
            // 添加菜单到菜单栏
            menuStrip.Items.AddRange(new ToolStripItem[] 
            {
                gameMenu, settingsMenu, helpMenu
            });
            
            // 设置菜单栏
            this.MainMenuStrip = menuStrip;
            this.Controls.Add(menuStrip);
        }

        /// <summary>
        /// 新游戏菜单项点击事件
        /// </summary>
        private void NewGame_Click(object sender, EventArgs e)
        {
            if (gameEngine.CurrentState == GameState.Menu)
            {
                gameEngine.StartGame();
            }
        }

        /// <summary>
        /// 暂停菜单项点击事件
        /// </summary>
        private void Pause_Click(object sender, EventArgs e)
        {
            if (gameEngine.CurrentState == GameState.Playing)
            {
                gameEngine.PauseGame();
            }
        }

        /// <summary>
        /// 继续菜单项点击事件
        /// </summary>
        private void Resume_Click(object sender, EventArgs e)
        {
            if (gameEngine.CurrentState == GameState.Paused)
            {
                gameEngine.ResumeGame();
            }
        }

        /// <summary>
        /// 演示模式菜单项点击事件
        /// </summary>
        private void Demo_Click(object sender, EventArgs e)
        {
            if (gameEngine.CurrentState == GameState.Menu)
            {
                gameEngine.StartDemoMode();
            }
        }

        /// <summary>
        /// 退出菜单项点击事件
        /// </summary>
        private void Exit_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        /// <summary>
        /// 游戏设置菜单项点击事件
        /// </summary>
        private void GameSettings_Click(object sender, EventArgs e)
        {
            using (var settingsForm = new SettingsForm())
            {
                if (settingsForm.ShowDialog() == DialogResult.OK)
                {
                    // 应用设置到游戏引擎
                    GameSettings.Instance.ApplyToGameEngine(gameEngine);
                }
            }
        }

        /// <summary>
        /// 游戏统计菜单项点击事件
        /// </summary>
        private void Statistics_Click(object sender, EventArgs e)
        {
            using (var statisticsForm = new StatisticsForm(gameEngine))
            {
                statisticsForm.ShowDialog();
            }
        }

        /// <summary>
        /// 关于菜单项点击事件
        /// </summary>
        private void About_Click(object sender, EventArgs e)
        {
            MessageBox.Show(
                "星际躲避游戏 v1.0\n\n" +
                "一个简单而有趣的太空躲避游戏。\n" +
                "使用方向键控制飞船，躲避陨石，挑战最高分！\n\n" +
                "功能特性：\n" +
                "• 多种游戏模式\n" +
                "• 音效和背景音乐\n" +
                "• 粒子特效\n" +
                "• 成就系统\n" +
                "• 高分记录\n" +
                "• 游戏统计\n\n" +
                "享受游戏，挑战极限！",
                "关于游戏",
                MessageBoxButtons.OK,
                MessageBoxIcon.Information);
        }

        /// <summary>
        /// 成就解锁事件处理
        /// </summary>
        private void OnAchievementUnlocked(Achievement achievement)
        {
            if (GameSettings.Instance.ShowAchievementNotifications)
            {
                // 在游戏界面显示成就通知
                this.BeginInvoke(new Action(() =>
                {
                    MessageBox.Show(
                        string.Format("🎉 成就解锁！\n\n{0}\n{1}", 
                            achievement.Name, achievement.Description),
                        "成就解锁",
                        MessageBoxButtons.OK,
                        MessageBoxIcon.Information);
                }));
            }
        }

        /// <summary>
        /// 键盘按下事件
        /// </summary>
        private void Form1_KeyDown(object sender, KeyEventArgs e)
        {
            int keyCode = (int)e.KeyCode;
            if (keyCode < keyStates.Length && !keyStates[keyCode])
            {
                keyStates[keyCode] = true;
                gameEngine.HandleKeyInput(e.KeyCode, true);
            }
            e.Handled = true;
        }
        
        /// <summary>
        /// 键盘释放事件
        /// </summary>
        private void Form1_KeyUp(object sender, KeyEventArgs e)
        {
            int keyCode = (int)e.KeyCode;
            if (keyCode < keyStates.Length)
            {
                keyStates[keyCode] = false;
                gameEngine.HandleKeyInput(e.KeyCode, false);
            }
            e.Handled = true;
        }
        
        /// <summary>
        /// 绘制事件
        /// </summary>
        private void Form1_Paint(object sender, PaintEventArgs e)
        {
            // 使用双缓冲绘图
            Graphics g = bufferedGraphics.Graphics;
            
            // 渲染游戏
            gameEngine.Render(g);
            
            // 将缓冲内容复制到屏幕
            bufferedGraphics.Render(e.Graphics);
        }
        
        /// <summary>
        /// 游戏状态改变事件
        /// </summary>
        private void OnGameStateChanged(GameState newState)
        {
            // 可以在这里添加状态改变时的逻辑
            switch (newState)
            {
                case GameState.Menu:
                    this.Text = "星际躲避游戏 - 主菜单";
                    Invalidate(); // 强制重绘菜单
                    break;
                case GameState.Playing:
                    this.Text = "星际躲避游戏 - 游戏中";
                    break;
                case GameState.Paused:
                    this.Text = "星际躲避游戏 - 暂停";
                    Invalidate(); // 强制重绘暂停界面
                    break;
                case GameState.GameOver:
                    this.Text = "星际躲避游戏 - 游戏结束";
                    Invalidate(); // 强制重绘游戏结束界面
                    break;
            }
        }
        
        /// <summary>
        /// 游戏时间更新事件
        /// </summary>
        private void OnGameTimeUpdated(float gameTime)
        {
            // 可以在这里添加时间更新时的逻辑
        }
        
        /// <summary>
        /// 游戏结束事件
        /// </summary>
        private void OnGameOver()
        {
            // 可以在这里添加游戏结束时的逻辑
        }
        
        /// <summary>
        /// 演示重启请求事件处理
        /// </summary>
        private void OnDemoRestartRequested()
        {
            // 确保在UI线程中执行
            if (this.InvokeRequired)
            {
                this.Invoke(new Action(OnDemoRestartRequested));
                return;
            }
            
            // 重启演示模式
            gameEngine.StartDemoMode();
        }
        
        /// <summary>
        /// 窗体关闭事件
        /// </summary>
        protected override void OnFormClosing(FormClosingEventArgs e)
        {
            // 释放游戏引擎资源
            if (gameEngine != null) gameEngine.Dispose();
            if (bufferedGraphics != null) bufferedGraphics.Dispose();
            if (context != null) context.Dispose();
            base.OnFormClosing(e);
        }
        
        /// <summary>
        /// 窗体大小改变事件
        /// </summary>
        protected override void OnResize(EventArgs e)
        {
            base.OnResize(e);
            
            // 重新创建双缓冲以适应新的窗体大小
            if (bufferedGraphics != null)
            {
                bufferedGraphics.Dispose();
                context.MaximumBuffer = new Size(ClientSize.Width + 1, ClientSize.Height + 1);
                bufferedGraphics = context.Allocate(CreateGraphics(), 
                    new Rectangle(0, 0, ClientSize.Width, ClientSize.Height));
            }
            
            // 重置游戏引擎的缓存
            if (gameEngine != null)
            {
                gameEngine.ResetStarfieldCache();
                gameEngine.ResetOffscreenBuffer();
            }
        }
    }
}
